/* 
 *  Copyright 2009-2010 Michal Trzcinka
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software distributed
 *  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *  CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *  specific language governing permissions and limitations under the License.
 */
YAHOO.namespace('TRZCINKA.VCARD');

(function() {

  var Dom = YAHOO.util.Dom,
  ContextMenu = YAHOO.widget.ContextMenu,
  Dialog = YAHOO.widget.Dialog,
  ColorPicker = YAHOO.widget.ColorPicker,
  LOGGER = new YAHOO.widget.LogWriter('context_menu.js'),
  Map = YAHOO.TRZCINKA.VCARD.Map;

  /**
   * GridContextMenu
   */

  YAHOO.namespace('TRZCINKA.VCARD.CONTEXT_MENU');
  YAHOO.namespace('TRZCINKA.VCARD.CONTEXT_MENU.ITEMS');

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.createItem = function(gridModel, location) {
    return {
      text: I18n.t('editor.context_menu.create_item'),
      onclick: {
        fn: function() {
          YAHOO.TRZCINKA.VCARD.Item._editor.show('', function(newContent) {
            gridModel.saveItem(location, newContent);
          });
        }
      }
    };
  };

  var CreateItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.createItem;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.removeItem = function(gridModel, location) {
    return {
      text: I18n.t('editor.context_menu.remove_item'),
      onclick: {
        fn: function() {
          gridModel.removeItem(location);
        }
      }
    };
  };

  var RemoveItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.removeItem;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.setTopItem = function(gridModel, location) {
    var items = gridModel.getItems(location);
    var topItem = gridModel.getTopItem(location);
    var itemdata = items.collect(function(item) {
      return {
        text: item.text,
        checked: item == topItem,
        onclick: {
          fn: function() {
            gridModel.setTopItem(location, item.order);
          }
        }
      };
    });
    return {
      text: I18n.t('editor.context_menu.set_top_item'),
      submenu: {
        id: Dom.generateId(),
        lazyload: true,
        itemdata: itemdata
      }
    };
  };

  var SetTopItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.setTopItem;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.COLORS = new Map({
    'Black': 'black',
    'White': 'white',
    'Red': 'red',
    'Blue': 'blue',
    'Green':'green',
    'Cyan': 'cyan',
    'Magenta': 'magenta',
    'Yellow': 'yellow'
  });

  var COLORS = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.COLORS;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.setOtherColor = function(setColorHandler) {
    return {
      text: I18n.t('editor.context_menu.set_color.other'),
      onclick: {
        fn: function() {

          this.dialog = new Dialog(Dom.generateId(), {
            width : "500px",
            close: false,
            fixedcenter : true,
            visible : true,
            constraintoviewport : true,
            modal: true,
            buttons : [
            {
              text: I18n.t('editor.context_menu.set_color.other_color_dialog.ok'),
              isDefault:true,
              handler: function() {
                setColorHandler('#' + Dom.get(this.picker.ID.HEX).value);
                this.destroy();
              }
            },
            {
              text: I18n.t('editor.context_menu.set_color.other_color_dialog.cancel'),
              handler: function() {
                this.destroy();
              }
            }
            ]
          });

          Dom.addClass(this.dialog.element, 'yui-picker-panel');

          this.dialog.setBody('');
          var el = document.createElement('div');
          el.id = 'yui-picker';
          Dom.addClass(el, 'yui-picker');
          this.dialog.body.appendChild(el);

          // Once the Dialog renders, we want to create our Color Picker
          // instance.
          this.dialog.renderEvent.subscribe(function() {
            if (!this.picker) { //make sure that we haven't already created our Color Picker
              this.picker = new ColorPicker('yui-picker', {
                container: this.dialog,
                images: {
                  PICKER_THUMB: "/yui/colorpicker/assets/picker_thumb.png",
                  HUE_THUMB: "/yui/colorpicker/assets/hue_thumb.png"
                },
                ids: ColorPicker.prototype.ID
              });
            }
          });

          this.dialog.render(document.body);

        }
      }
    };
  };

  var SetOtherColor = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.setOtherColor;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.setColors = function(gridModel, location) {
    var item = gridModel.getTopItem(location);

    var bgColorMenuItems = [];
    var fgColorMenuItems = [];

    var setBgColor = function(color) {
      gridModel.updateItem(location, {
        backgroundColor: color
      });
    };
    var setFgColor = function(color) {
      gridModel.updateItem(location, {
        foregroundColor: color
      });
    };

    COLORS.each(function(pair) {
      var color = pair.value;
      var colorName = pair.key;
      bgColorMenuItems.push({
        text: colorName,
        checked: item.backgroundColor == color,
        onclick: {
          fn: function(
            event, eventName, color) {
            setBgColor(color);
          },
          obj: color
        }
      });
      fgColorMenuItems.push({
        text: colorName,
        checked: item.foregroundColor == color,
        onclick: {
          fn: function(
            event, eventName, color) {
            setFgColor(color);
          },
          obj: color
        }
      });
    });
    bgColorMenuItems.push(new SetOtherColor(setBgColor));
    fgColorMenuItems.push(new SetOtherColor(setFgColor));

    return {
      fg:
      {
        text: I18n.t('editor.context_menu.set_color.set_foreground_color'),
        submenu: {
          id: Dom.generateId(),
          lazyload: true,
          itemdata: fgColorMenuItems
        }
      },
      bg:
      {
        text: I18n.t('editor.context_menu.set_color.set_background_color'),
        submenu: {
          id: Dom.generateId(),
          lazyload: true,
          itemdata: bgColorMenuItems
        }
      }
    };
  };

  var SetColors = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.setColors;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.linkItem = function(gridModel, location) {
    return {
      text: I18n.t('editor.context_menu.link_item'),
      onclick: {
        fn: function() {
          gridModel.startLinking(location);
        }
      }
    };
  };

  var LinkItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.linkItem;



  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.unlinkItem = function(gridModel, location, locations) {
    var subItems = locations.collect(function(otherLocation) {
      return {
        text: gridModel.getTopItem(otherLocation).text,
        onclick: {
          fn: function() {
            gridModel.unlinkItem(location, otherLocation);
          }
        }
      }
    });

    return {
      text: I18n.t('editor.context_menu.unlink_item'),
      submenu: {
        id: Dom.generateId(),
        lazyload: true,
        itemdata: subItems
      }
    }
  }

  var UnlinkItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.unlinkItem;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.duplicateItem = function(gridModel, location) {
    return {
      text: I18n.t('editor.context_menu.duplicate_item'),
      onclick: {
        fn: function() {
          gridModel.startDuplication(location);
        }
      }
    }
  }

  var DuplicateItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.duplicateItem;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.highlightItem = function(gridModel, location) {
    return {
      text: I18n.t('editor.context_menu.highlight_item'),
      onclick: {
        fn: function() {
          gridModel.updateItem(location, {
            isHighlighted: true
          });
        }
      }
    }
  }

  var HighlightItem = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.highlightItem;

  YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.disableItemHighlight = function(gridModel, location) {
    return {
      text: I18n.t('editor.context_menu.disable_item_highlight'),
      onclick: {
        fn: function() {
          gridModel.updateItem(location, {
            isHighlighted: false
          });
        }
      }
    }
  }

  var DisableItemHighlight = YAHOO.TRZCINKA.VCARD.CONTEXT_MENU.ITEMS.disableItemHighlight;

  YAHOO.TRZCINKA.VCARD.buildContextMenu = function(tableId, gridModel) {

    var ctxMenu = new ContextMenu(Dom.generateId(), {
      trigger: tableId,
      lazyload: true,
      zindex: 100
    });
    ctxMenu.subscribe('beforeShow', function() {
      if (this == ctxMenu) {  // check if the event is fired by the root menu, not a submenu
        this.clearContent();
        var cell;
        if (this.contextEventTarget.tagName == 'TD') {
          cell = this.contextEventTarget;
        } else {
          cell = Dom.getAncestorByTagName(this.contextEventTarget, 'TD');
        }
        var location = cell.id.fromGridLocation();
        if (!gridModel.itemExists(location)) { //add 'create' option to the menu
          this.addItem(new CreateItem(gridModel, location));
        } else { //add other
          var setColors = new SetColors(gridModel, location);
          this.addItems([new RemoveItem(gridModel, location), new DuplicateItem(gridModel, location),
            setColors.fg, setColors.bg, new LinkItem(gridModel, location)]);
          if (gridModel.isStack(location)) {
            this.addItem(new SetTopItem(gridModel, location));
          }
          var links = gridModel.getLinkLocations(location);
          if (links.length > 0) {
            this.addItem(new UnlinkItem(gridModel, location, links));
          }
          if (gridModel.isHighlighted(location)) {
            this.addItem(new DisableItemHighlight(gridModel, location));
          } else {
            this.addItem(new HighlightItem(gridModel, location));
          }
        }
        this.render();
      }
    });
  };

})();
